package com.example.atomics;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * netty源码里面用到了这个
 */
class BankAccount {
    //1 更新的对象属性必须使用 public volatile 修饰符。
    public volatile int money = 0;

    //以一种线程安全的方式操作非线程安全对象内的某些字段
    String bankName = "ccb";
    //2 因为对象的属性修改类型原子类都是抽象类，所以每次使用都必须
    // 使用静态方法newUpdater()创建一个更新器，并且需要设置想要更新的类和属性。
    static AtomicIntegerFieldUpdater<BankAccount> FieldUpdater = AtomicIntegerFieldUpdater.newUpdater(BankAccount.class, "money");

    public void transfer(BankAccount bankAccount) {
        FieldUpdater.incrementAndGet(bankAccount);
    }
}


@Slf4j
public class AtomicIntegerFieldUpdaterDemo {
    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        BankAccount bankAccount = new BankAccount();
        CountDownLatch latch = new CountDownLatch(1000);
        for (int i = 1; i <= 1000; i++) {
            new Thread(() -> {
                bankAccount.transfer(bankAccount);
                latch.countDown();
            }, "Thread-" + i).start();
        }
        latch.await();
        log.info("cost:{}ms", System.currentTimeMillis() - start);
        log.info("---bankAccount: {}", bankAccount.money);
    }
}
